package com.silentfish.backend.codeGenerator.creator;

import com.silentfish.backend.codeGenerator.bean.Conf;
import com.silentfish.backend.codeGenerator.bean.GenFileInfo;
import com.silentfish.backend.codeGenerator.bean.TableInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public abstract class AbstractFileCreator implements FileCreator {

    protected static Configuration cfg;
    protected static Conf conf = null;

    static {
        cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setClassLoaderForTemplateLoading(AbstractFileCreator.class.getClassLoader(), "codeGenerator/templates");
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    }

    /**
     */
    protected GenFileInfo createFile(Template temp, TableInfo tableInfo) throws IOException, TemplateException {

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        String fileName = this.getFileName(tableInfo);

        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("table", tableInfo);
        dataModel.put("conf", conf);
        temp.process(dataModel, new OutputStreamWriter(os, StandardCharsets.UTF_8));

        GenFileInfo genFileInfo = new GenFileInfo();
        genFileInfo.setOs(os);
        genFileInfo.setFileName(fileName);
        return genFileInfo;
    }

    @Override
    public GenFileInfo createFile(TableInfo tableInfo) throws IOException, TemplateException {
        String ftl = getTempletName();
        // String fileName = getFilePath(tableInfo);
        Template temp = cfg.getTemplate(ftl);
        setPackageName(tableInfo);
        return createFile(temp, tableInfo);
    }

    public static void init(Conf _conf) {
        if (conf == null) {
            conf = _conf;
        }
    }
}
